package com.example.xwadmin.api.ai;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xw.common.entity.Weibo;
import com.example.xw.common.service.WeiboService;
import com.example.xw.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Component
public class Scheduler {

    @Autowired
    private TaskScheduler taskScheduler;
    @Autowired
    private WeiboService weiboService;

    @PostConstruct
    public void scheduleTask() {
        Runnable task = () -> {
            try {
                judge();
            } catch (NoApiKeyException | InputRequiredException e) {
                e.printStackTrace();
            }
        };
        Date startTime = new Date(System.currentTimeMillis()); // 10秒后开始
        taskScheduler.scheduleWithFixedDelay(task, startTime, 5000); // 初始延迟后每5秒执行一次
    }


    public void judge() throws NoApiKeyException, InputRequiredException {

        //获取待审核的微博
        int pageNum = 1;
        int pageSize = 10;
        String orderField = "";


        boolean hasMore = true;
        while (hasMore) {
            System.err.println("pageNum:"+pageNum);
            Result<Page<Weibo>> page = weiboService.findList(pageNum, pageSize, orderField, 0);
            if (page.getCode() != 2000) {
                break;
            }


//            System.out.println(page);
            Page<Weibo> data = page.getData();
            List<Weibo> records = data.getRecords();
            System.err.println(records.size());

            if (records.isEmpty()) {
                hasMore = false; // 没有更多记录
            } else {
                for (Weibo weibo : records) {
                    //调用AI接口
                    int i = AiJudge.callWithMessage(weibo.getContent());
                    System.err.println(weibo.getId()+":"+i);
                    if (i == 1) {
                        //审核通过
                        weibo.setState(1);
                        System.err.println("审核通过");
                        weiboService.updateState(weibo.getId(), 1);
                    } else if(i == -1){
                        //审核不通过
                        weibo.setState(-1);
                        weiboService.updateState(weibo.getId(), -1);
                    } else{
                        //人工审核
                        weibo.setState(3);
                        weiboService.updateState(weibo.getId(), 3);
                    }
                }
            }
            pageNum++;
        }
    }
}
